import axios from "axios";
import { Message } from "element-ui";
import { logout } from "utils/user";

const codes = require("./errorCode");

const host = process.env.NODE_ENV === "development" ? "localhost:7001" : "localhost:7001";
const baseURL = process.env.NODE_ENV === "development" ? `http://${host}` : `http://${host}`;

// const hostname = window.location.hostname;

const api = axios.create({
  timeout: 60000,
  baseURL,
});

const responseSuccess = ({ data }) => {
  const successCode = data.success;
  const errorCode = data.error;
  const message = data.message;
  if (successCode && successCode === 200) {
    // Message({
    //   message: message,
    //   center: true,
    //   type: "success",
    // });
    return data.data;
  }

  if (errorCode && errorCode === 500) {
    Message({
      message: message,
      center: true,
      type: "error",
    });
  }

  return Promise.reject(data);
};

const responseFail = ({ response, ...others }) => {
  if (!response) {
    console.error(others); // eslint-disable-line
    return;
  }

  if (response.status === 401) {
    setTimeout(logout, 1000);
  }
  Message({
    message: codes[response.status],
    center: true,
    type: "error",
  });


  return Promise.reject(response);
};

api.interceptors.response.use(responseSuccess, responseFail);
api.interceptors.request.use();
const jwt = localStorage.getItem("Authorization") || "noToken";
const userInfo = localStorage.getItem("userInfo") || "{}";
const data = JSON.parse(userInfo);
api.defaults.headers.Authorization = `Bearer ${jwt}`;
api.defaults.headers.uploadpath = data.username || "images";

export default api;
